<!--Organization  -->
<template>
  <div class="organization content_box">
    <div class="header_row flex align-center flex-wrap" v-if="hasBtn('Organization:query')">
      <div class="flex align-center m-r-2">
        <span>公司名称：</span>
        <el-input v-model="searchObj.OrgName" placeholder="搜索方案名称" clearable></el-input>
      </div>

      <el-button type="primary" @click="(searchObj.currentPage = 1), getListFun()">查询</el-button>
    </div>

    <div class="m-b-1 neck_box flex align-center space-between">
      <div>
        <el-button type="success" @click="showDialog('add')" v-if="hasBtn('Organization:add')">新增组织</el-button>
        <!-- <el-button type="danger">批量删除</el-button> -->
        <el-button type="warning" disabled v-if="hasBtn('Organization:export')">导出列表</el-button>
      </div>
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="searchObj.currentPage" :max-height="tableHeight" :page-size="searchObj.pageSize" :page-sizes="[10, 20, 50, 100, 200]" layout="total,sizes, prev, pager, next, jumper" :total="pageTotal">
      </el-pagination>
    </div>
    <el-table :data="tableData" border stripe style="width: 100%" v-loading="tableLoading" @sort-change="sortChange" sortable="custom">
      <el-table-column fixed prop="index" label="序号" width="80" align="center">
      </el-table-column>
      <el-table-column prop="OrgName" label="公司名称" align="center" width="190" sortable>
      </el-table-column>
      <el-table-column prop="UserCount" label="公司用户数量" align="center" width="130" sortable>
      </el-table-column>
      <el-table-column prop="OrgCharge" label="公司负责人" align="center" sortable>
      </el-table-column>
      <el-table-column prop="OrgLevel" label="公司级别" align="center" sortable>
        <template slot-scope="scope">
          <div>
            {{findCom(scope.row.OrgLevel)}}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="OrgPhone" label="联系电话" align="center" sortable>
      </el-table-column>
      <el-table-column prop="OrgAddr" label="联系地址" align="center" sortable>
      </el-table-column>

      <el-table-column prop="Remark" label="备注" align="center" sortable>
      </el-table-column>
      <el-table-column label="是否有效" align="center" sortable>
        <template slot-scope="scope">
          <el-switch v-model="scope.row.IsActive" :disabled="!hasBtn('Organization:active')" @change="switchChange(scope.row.Id, scope.row.IsActive)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="250" align="center" v-if="hasBtn('Organization:edit') || hasBtn('Organization:delete')">
        <template slot-scope="scope">
          <el-button type="primary" v-if="hasBtn('Organization:edit')" size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button @click="handleDelete(scope.$index, scope.row)" v-if="hasBtn('Organization:delete')" type="danger" size="small">删除</el-button>
          <!-- <el-button
            @click="
              dialogVisible2 = true;
              RoleId = scope.row.Id;
            "
            type="success"
            size="small"
            >分润配置</el-button
          > -->
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :title="dialogTitle" class="dialog" :visible.sync="dialogVisible" width="30%" v-if="dialogVisible">
      <el-tabs v-model="activeName">
        <el-tab-pane label="基础信息" name="first">
          <el-form v-loading="calcLoaing" ref="dataForm" :rules="rules" :model="addObj" label-position="right" label-width="140px">
            <el-form-item label="公司名称：" prop="OrgName">
              <el-input class="flex-1" v-model="addObj.OrgName"></el-input>
            </el-form-item>
            <el-form-item label="公司级别：" prop="OrgLevel">
              <el-select v-model="addObj.OrgLevel" placeholder="请选择" class="flex-1" style="width: 100%">
                <el-option v-for="item in OrgLevelOptions" :key="item.EnumName" :label="item.Desction" :value="item.EnumName">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="管辖地区：" prop="OrgAddr" v-if="addObj.OrgLevel == 'Province' && dialogType == 'edit'">
              <template v-if="findMyAreas.length == 0">
                <span class="m-r-2">暂无</span>
              </template>
              <template v-else>
                <span class="cityItemSpan" v-for="(item, index) of findMyAreas" :key="index">{{ item }}</span>
              </template>
              <el-button type="text m-l-1" v-loading="secondloading" @click="showAreasSelectFun">修改</el-button>
            </el-form-item>
            <el-form-item label="佣金结算百分比：" prop="SettlePer" v-if="addObj.OrgLevel == 'Province' ">
              <el-input type="number" v-model="addObj.SettlePer" class="flex-1" min="0" @keyup.native="proving2($event, '%')">
                <template slot="append">%</template>
              </el-input>
            </el-form-item>
            <el-form-item label="选择地区：" prop="Areas" v-if="addObj.OrgLevel == 'Province' && showAreasSelect">
              <el-cascader style="width: 100%" class="flex-1" v-model="Areas" :options="AreaList" :props="props" collapse-tags clearable></el-cascader>
            </el-form-item>
            <!--  -->
            <el-form-item label="上级公司：" prop="OrgParentId">
              <el-select v-model="addObj.OrgParentId" filterable remote reserve-keyword placeholder="请输入关键词搜索" :remote-method="remoteMethod" :loading="Selloading">
                <el-option v-for="item in queryOptions" :key="item.Id" :label="item.OrgName" :value="item.Id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="公司负责人：" prop="OrgCharge">
              <el-input class="flex-1" v-model="addObj.OrgCharge"></el-input>
            </el-form-item>
            <el-form-item label="联系电话：" prop="OrgPhone">
              <el-input class="flex-1" v-model="addObj.OrgPhone"></el-input>
            </el-form-item>
            <el-form-item label="公司地址：" prop="OrgAddr">
              <el-input class="flex-1" v-model="addObj.OrgAddr"></el-input>
            </el-form-item>

            <el-form-item label="备注：" prop="Remark">
              <el-input type="textarea" class="flex-1" v-model="addObj.Remark" placeholder="请输入内容" maxlength="30" show-word-limit></el-input>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="结算配置" name="second">
          <el-row class="header_row" :gutter="30" v-for="item of typeOption" :key="item.OrderType">
            <el-col :span="12">
              <div class="flex align-center">
                <span class="tit_span nowarp">配置名称：</span>
                <span>{{ item.Desction }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="flex align-center">
                <span class="tit_span nowarp">结算百分比：</span>
                <el-input type="number" v-model="item.Percentage">
                  <template slot="append">%</template>
                </el-input>
              </div>
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>

      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDia">取 消</el-button>
        <el-button type="primary" @click="saveData">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog class="dialog" :visible.sync="dialogVisible2" width="800px" v-if="dialogVisible2">
      <idpower-edit :RoleId="RoleId" :IsSystem="3" :alldisabled2="false"></idpower-edit>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible2 = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible2 = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import { getList, save, deleteApi, valid, GetOrgLevel, GetAreaList, GetById } from '@/api/organization'
  import idpowerEdit from '@/views/UserManage/components/identityPowerEdit.vue'
  import { GetOrderType } from '@/api/system/share-manage'
  export default {
    //import引入的组件需要注入到对象中才能使用
    name: 'organization',
    components: { idpowerEdit },
    data() {
      //这里存放数据
      return {
        tableHeight: 0,
        activeName: "first",
        RoleId: '',
        tableLoading: false,
        dialogVisible: false,
        dialogVisible2: false,
        Selloading: false,//下拉搜索的加载动效
        queryOptions: [],
        showAreasSelect: false,//是否显示城市选择
        secondloading: false,//点击修改城市时候 显示加载动效 
        dialogType: "add",
        searchObj: {
          OrgName: "",
          currentPage: 1,
          pageSize: 10,
        },
        pageTotal: 0,
        tableData: [],
        rules: {
          OrgName: [
            { required: true, message: '必填', trigger: 'blur' },
          ],
          SettlePer: [{ required: true, message: '必填', trigger: 'blur' },],
          OrgCharge: [
            { required: true, message: '必填', trigger: 'blur' },
          ],
          OrgPhone: [
            { required: true, message: '必填', trigger: 'blur' },
          ],
          OrgAddr: [
            { required: true, message: '必填', trigger: 'blur' },
          ],
          OrgLevel: [
            { required: true, message: '必填', trigger: 'blur' },
          ],
          OrgParentId: [{ required: true, message: '必填', trigger: 'blur' },],
          Areas: [
            { required: true, message: '必填', trigger: 'blur' },
          ],
        },
        addObj: {},
        OrgLevelOptions: [],
        allCity: [],
        AreaListOptions: [],
        AreaList: [],
        Areas: [],
        props: { multiple: true, value: 'Id', label: 'Name', children: 'ChildList' },
        typeOption: []
      };
    },
    //监听属性 类似于data概念
    computed: {
      dialogTitle() {
        return this.dialogType == 'add' ? '新增' : '编辑'
      },
      calcLoaing() {
        if (this.dialogType == 'add') {
          return this.AreaListOptions.length == 0
        } else {
          return !this.addObj.OrgName
        }
      },

      findMyAreas() {
        // this.Areas
        let Areas = this.Areas
        let objlist = []
        if (this.addObj.OrgLevel == 'Province') {
          if (Areas.length > 0) {
            for (let item of Areas) {
              if (!item[0] && item[1]) {
                let cItem = this.allCity.find(_ => _.Id == item[1])
                objlist.push(cItem.Name)
              } else {
                let parentItem = this.allCity.find(_ => _.Id == item[0])
                if (parentItem && parentItem.ChildList) {
                  let obj = parentItem.ChildList.find(_ => _.Id == item[1])
                  objlist.push(obj.Name)
                }
              }

            }
          }
        }
        return objlist
      }
    },
    //监控data中的数据变化
    watch: {
      "addObj.OrgLevel": {
        handler: function (a, b) {
          let that = this
          let timerI = setInterval(() => {
            if (!this.AreaListOptions || this.AreaListOptions.length <= 0) {
              // console.log('等待')
            } else {
              clearInterval(timerI)
              task()
            }
          }, 800)
          function task() {
            switch (a) {
              case 'Province':
                that.AreaList = that.AreaListOptions.map(item => {
                  let cl = item.ChildList.map(cell => {
                    return { ...cell, ChildList: null }
                  })
                  return { ...item, ChildList: cl }
                })
                break
              // case 'Province':这是旧版   旧版中 上面的代码 是case 'City'
              //   that.AreaList = that.AreaListOptions.map(item => {
              //     return { ...item, ChildList: null }
              //   })
              //   break
              default:
                that.AreaList = that.AreaListOptions
            }
          }

        }
      },

    },
    //方法集合
    methods: {
      closeDia() {
        this.dialogVisible = false;
        this.showAreasSelect = false;
        this.typeOption = this.originalTypeOption
        this.activeName = "first"
      },
      GetOrderTypeFun() {
        return new Promise((next) => {
          this.loading = true
          GetOrderType({}).then(res => {
            // console.log(res)
            this.originalTypeOption = this.typeOption = res.Data.map(item => {
              return { OrderType: item.EnumName, Desction: item.Desction, Percentage: 0, Id: '00000000-0000-0000-0000-000000000000' }
            })
            next()
          })
        })
      },

      remoteMethod(query) {
        if (query !== '') {
          this.Selloading = true;
          getList({
            "OrgName": query, //	公司名称
            "IsPaging": true, //是否分页
            'PageIndex': 1,
            'PageSize': 100,
          }).then(res => {
            this.Selloading = false;
            if (res.Data && res.Data.length > 0) {
              this.queryOptions = res.Data
              this.queryOptions.unshift({ Id: '00000000-0000-0000-0000-000000000000', OrgName: '无上级' })
            } else {
              this.queryOptions = [{ Id: '00000000-0000-0000-0000-000000000000', OrgName: '无上级' }];
            }

          })
        }
      },
      getQueryOption() {
        getList({
          "IsPaging": true, //是否分页
          'PageIndex': 1,
          'PageSize': 30,
        }).then(res => {
          if (res.Data && res.Data.length > 0) {
            this.queryOptions = res.Data
            this.queryOptions.unshift({ Id: '00000000-0000-0000-0000-000000000000', OrgName: '无上级' })
          } else {
            this.queryOptions = [{ Id: '00000000-0000-0000-0000-000000000000', OrgName: '无上级' }];
          }
        })
      },
      async GetOrgLevelFun() {
        let { Data } = await GetOrgLevel()
        this.OrgLevelOptions = Data
      },
      async GetAreaListFun(_boolean) {
        let { Data } = await GetAreaList({ 'IsFilter': _boolean })
        if (_boolean) {
          //过滤了的 进入下拉框
          this.AreaListOptions = Data.filter(item => item.ChildList.length != 0)
        } else {
          //未过滤的 留作编辑页中城市的摄取 显示在dialog中
          this.allCity = Data
        }

      },
      switchChange(id, IsActive) {
        valid({ Id: id }).then(_ => {
          this.$notify({
            title: '切换成功',
            message: 'success',
            type: 'success',
            duration: 2000
          })
          this.getListFun()
        })
      },
      findCom(e) {
        if (this.OrgLevelOptions.length > 0) {
          let obj = this.OrgLevelOptions.find(_ => _.EnumName == e)
          return obj.Desction || '无'
        }
      },
      showDialog(type) {
        if (type == 'add') {

          this.addObj = {
            "Id": "00000000-0000-0000-0000-000000000000",
            "OrgParentId": "00000000-0000-0000-0000-000000000000", //公司父Id，没上级可为空值Guid
            "OrgName": "", //公司名称
            "OrgCharge": "", //负责人
            "OrgPhone": "", //联系电话
            "OrgAddr": "", //公司地址
            "OrgLevel": "",
            "SettlePer": 0,//佣金结算百分比
            "Areas": [],
            "Remark": "",
          }
          this.showAreasSelectFun()

        }
        this.dialogType = type
        this.dialogVisible = true

      },
      dealAreas() {
        //生成接口需要的格式
        let newAreas = []
        let Areas = this.Areas
        let newAreasList = this.dealAreaListOptions(this.allCity)
        switch (this.addObj.OrgLevel) {
          case 'Province': //this.Areas有两层 如[10000,11000]
            for (let item of Areas) {
              let obj = newAreasList.find(cell => cell.Id == item[1])
              newAreas.push({ "AreaId": obj.Id, "AreaName": obj.Name })
            }
            break
        }
        return newAreas
      },
      dealAreaListOptions(list) {
        let newAreas = []
        function createdList(mlist) {
          for (let item of mlist) {
            let obj = { "Id": item.Id, "Name": item.Name }
            item.ParentId && (obj.ParentId = item.ParentId)
            newAreas.push(obj)
            if (item.ChildList && item.ChildList.length > 0) {
              createdList(item.ChildList)
            }
          }
        }
        createdList(list)
        return newAreas
      },
      saveData() {
        // console.log(this.addObj)
        for (let item in this.addObj) {
          if (['Remark'].includes(item)) continue
          if (!this.addObj[item] && (this.$getType(this.addObj[item]) !== 'Number')) {
            // console.log(item)
            this.$notify({
              title: '提示',
              message: '请填写完整信息',
              type: 'warning',
              duration: 2000
            })
            return
          }
        }
        let addObj = this.$deepClone(this.addObj)
        addObj.Areas = this.dealAreas()
        if (addObj.OrgLevel == 'Province' && addObj.Areas.length <= 0) {
          this.$notify({
            title: '提示',
            message: '请选择管辖地区',
            type: 'warning',
          })
          return
        }
        if (addObj.OrgLevel == 'City' || addObj.OrgLevel == 'HeadOffice') {
          delete addObj.Areas
          delete addObj.SettlePer
        }
        addObj.MallSettlements = this.$deepClone(this.typeOption)

        save(addObj).then(res => {
          this.$notify({
            title: '保存成功',
            message: 'success',
            type: 'success',
            duration: 2000
          })
          this.getListFun()
          this.dialogVisible = false
          this.showAreasSelect = false
        }).catch(err => {

        })
      },
      handleSizeChange(val) {
        this.searchObj.pageSize = val
        this.getListFun()
      },
      handleCurrentChange(val) {
        this.searchObj.currentPage = val
        this.getListFun()
      },

      async handleEdit(index, row) {
        this.showDialog('edit')
        this.Areas = []
        let { Data } = await GetById({ Id: row.Id })
        let splist = this.dealAreaListOptions(this.allCity)
        let Areas = []
        // console.log(splist)
        if (Data.OrgLevel == 'Province') { // [10000,11000] 市级 省级
          for (let item of Data.Areas) {
            let oj = splist.find(_ => _.Id == item.AreaId)
            if (oj) {
              Areas.push([oj.ParentId, item.AreaId])
            } else {
              continue
            }
          }

          this.Areas = Areas
        }
        // else if (Data.OrgLevel == 'Province') { // 11000 省级
        //   Areas = Data.Areas.map(item => {
        //     return item.AreaId
        //   })
        // }
        this.addObj = {
          "Id": Data.Id,
          "OrgParentId": Data.OrgParentId, //公司父Id，没上级可为空值Guid
          "OrgName": Data.OrgName, //公司名称
          "OrgCharge": Data.OrgCharge, //负责人
          "OrgPhone": Data.OrgPhone, //联系电话
          "OrgAddr": Data.OrgAddr, //公司地址
          "OrgLevel": Data.OrgLevel,
          "SettlePer": Data.SettlePer,
          "Areas": Data.Areas,
          "Remark": Data.Remark,
        }
        let options = this.$deepClone(this.originalTypeOption)
        this.typeOption = options.map(item => {
          for (let cell of Data.MallSettlements) {
            if (cell.OrderType == item.OrderType) {
              item.Percentage = cell.Percentage
              item.Id = cell.Id
            }
          }
          return { ...item }
        })
      },
      handleDelete(index, row) {
        this.$confirm('确认删除此条数据吗？').then(_ => {
          let obj = {
            Id: row.Id
          }
          deleteApi(obj).then(res => {

            this.$notify({
              title: '删除成功',
              message: 'success',
              type: 'success',
              duration: 2000
            })
            this.tableData.splice(index, 1)
            this.pageTotal -= 1
          })
        })


      },
      sortChange(e) {
        let SortType = false
        if (e.order == "ascending") {
          SortType = true
        }
        this.getListFun(e.prop, SortType)
      },
      getListFun(SortName = 'CreateDate', SortType = true) {
        let currentPage = this.searchObj.currentPage
        this.tableLoading = true
        let searchObj = this.$deepClone(this.searchObj)
        let obj = {
          "OrgName": searchObj.OrgName, //	公司名称
          "IsPaging": true, //是否分页
          "SortName": SortName, //排序栏位
          "SortType": SortType,//排序类型｛True：正序；Flase：反序｝
          'PageIndex': currentPage,
          "PageSize": searchObj.pageSize,
        }


        getList(obj).then(res => {
          this.tableData = res.Data.map((item, index) => {
            for (let cell in item) {
              if (!item[cell] && this.$getType(item[cell]) !== 'Number') {
                item[cell] = '-'
              }
            }
            return { ...item, index: (index + 1) + ((currentPage - 1) * 10) }
          })
          this.pageTotal = res.Total
          this.tableLoading = false
        }).catch(_ => {
          this.tableLoading = false
          this.tableData = []
          this.pageTotal = 0
        })
      },
      showAreasSelectFun() {
        this.AreaListOptions = []
        this.secondloading = true
        this.GetAreaListFun(true).then(_ => {
          this.showAreasSelect = true
          this.secondloading = false
        })
      }
    },
    //生命周期 - 创建完成（可以访问当前this实例）
    created() {
      this.getListFun()
      this.GetOrgLevelFun()
      this.GetAreaListFun(false) // 不过滤已经被选择的城市
      this.getQueryOption()
      this.GetOrderTypeFun()
    },
    //生命周期 - 挂载完成（可以访问DOM元素）
    mounted() {

    },
    beforeCreate() { }, //生命周期 - 创建之前
    beforeMount() { }, //生命周期 - 挂载之前
    beforeUpdate() { }, //生命周期 - 更新之前
    updated() { }, //生命周期 - 更新之后
    beforeDestroy() { }, //生命周期 - 销毁之前
    destroyed() { }, //生命周期 - 销毁完成
    activated() { }, //如果页面有keep-alive缓存功能，这个函数会触发
  }
</script>
//@import url(); 引入公共css类
<style  scoped>
  .cityItemSpan + .cityItemSpan::before {
    content: '，';
  }
</style>